package com.cmii.sjw.department.control.jsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmii.sjw.department.control.jsc.mapper.UniversityIndicatorsMapper;
import com.cmii.sjw.department.control.jsc.model.CountyIndicators;
import com.cmii.sjw.department.control.jsc.model.UniversityIndicators;
import com.cmii.sjw.department.control.jsc.model.vo.UniversityIndicatorVo;
import com.cmii.sjw.department.control.jsc.service.UniversityIndicatorsService;
import com.cmii.sjw.department.control.jsc.vo.CountyIndicatorsVO;
import com.cmii.sjw.department.control.jsc.vo.UniversityIndicatorsVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service("UniversityIndicatorsService")
public class UniversityIndicatorsServiceImpl extends ServiceImpl<UniversityIndicatorsMapper, UniversityIndicators> implements UniversityIndicatorsService {
    @Autowired
    private UniversityIndicatorsMapper universityIndicatorsMapper;

    @Override
    public Map<String, Map<String,Object>> listByUniversityIndicators(String secondLevelIndicatorName) {
        List<UniversityIndicators> list = universityIndicatorsMapper.selectList(
                new LambdaQueryWrapper<UniversityIndicators>()
                        .like(StringUtils.isNotBlank(secondLevelIndicatorName), UniversityIndicators::getSecondLevelIndicatorName, secondLevelIndicatorName)
                        .eq(UniversityIndicators::getIsDeleted, 0)
                        .orderByAsc(UniversityIndicators::getSubModule)
        );

        // 按 subModule 分组
        Map<String, List<UniversityIndicators>> grouped = list.stream()
                .collect(Collectors.groupingBy(UniversityIndicators::getSubModule));

        Map<String, Map<String, Object>> result = new HashMap<>();

        for (Map.Entry<String, List<UniversityIndicators>> entry : grouped.entrySet()) {
            String subModuleKey = toShortKey(entry.getKey());
            Map<String, Object> valuesMap = new LinkedHashMap<>();

            for (UniversityIndicators item : entry.getValue()) {
                String key = toEnglishIndicatorKey(item.getFirstLevelIndicatorName());
                valuesMap.put(key, item.getSecondLevelIndicatorValue());
            }

            result.put(subModuleKey, valuesMap);
        }

        return result;
    }

    /**
     * 高校指标1
     */
    @Override
    public Map<String, String> gxGzljytx(String highName) {
        // 空值检查
        List<UniversityIndicators> firstLevelList = Optional.ofNullable(universityIndicatorsMapper.selectList(
                new LambdaQueryWrapper<UniversityIndicators>()
                        .eq(UniversityIndicators::getSecondLevelIndicatorName, highName)
        )).orElse(Collections.emptyList());

        Map<String, String> retMap = new HashMap<>();

        // 使用Map来存储映射关系，提高可读性和性能
        Map<String, String> firstLevelMapping = new HashMap<String, String>() {{
            // 双一流、双高建设
            put("“双一流”建设入选高校", "syljsrxgx");
            put("国家高水平学校建设单位", "gjgspxxjsdw");
            put("国家高水平专业群建设单位", "gjgspzyqjsdw");
            put("市级高水平学校建设单位", "sjgspxxjsdw");
            put("市级高水平专业群建设单位", "sjgspzyqjsdw");

            // 学科专业建设
            put("硕士学位授权点", "ssxwsqd");
            put("博士学位授权点", "bsxwsqd");
            put("市级重点学科", "sjzdxk");
            put("“双一流”建设入选学科", "syljsrxxk");
            put("国家级一流本科专业建设点", "gjyylbkzyjsd");
            put("国家级一流本科课程", "gjyylbkkc");
            put("高水平“四新”建设高校", "gspsxjsgx");
            put("国家级教学成果奖", "gjjxcgj");
            put("本科高校教师教学创新比赛", "bkgxjsjxcxbs");
            put("专业点数", "zyds");
            put("专业设置与重点产业匹配度", "zyszzydcpphd");
            put("办学条件重点监测指标达标", "bxtjzdjcjzbd");
            put("国家级、市级教学成果奖数", "gjsjjxcgjs");
            put("建设国家级职业教育在线精品课程数", "jsgjzyjyzxjpkcs");
            put("建设国家级规划教材数", "jsgjghjcs");
            put("建设国家级、市级职业教育专业教学资源库数", "jsgjsjzyjyzyjxzykgs");
            put("建设国家级、市级产教融合实训基地、虚拟仿真实训基地数", "jsgjsjcjrhsxjdxnfzsxjdjs");
            put("培育国家级、市级职业教育教师教学创新团队数", "pygjsjzyjyjsjxcxtds");
            put("ESI前1‰学科", "esiqxk");

            // 教师队伍情况
            put("生师比", "ssb");
            put("“双师”型教师占比（%）", "ssxjszb");
            put("专任教师博士学历占比", "zrjsbsxlzb");

            // 科研平台
            put("国家级科研平台", "gjjkrypt");
            put("国家级项目", "gjkjxm");
            put("部委项目", "bwxm");
            put("其它科技项目", "qtkjxm");

            // 职普融通、产教融合
            put("贯通人才培养试点专业数", "gtrcpysdzys");
            put("贯通人才培养试点招生数", "gtrcpysdzss");
            put("牵头建设市域产教联合体数", "qtjssycjlhts");
            put("牵头建设行业产教融合共同体数", "qtjshycjrhgtts");
            put("建设市级职业教育现代产业学院数", "jssjzyjyxdcyxys");
            put("认定示范性职业教育集团数", "rdsfzyjyjts");
            put("国家级现代学徒制试点学校", "gjxdxtzxx");
            put("立项建设市级共性技术服务平台、产教融合供需平台、开放型区域产教融合实践中心数", "lxjssjgxjsfwptcjrhgxptkfxqycjrhsjzxs");
        }};


        // 初始化所有可能的key到retMap，默认值为空字符串
        firstLevelMapping.values().forEach(key -> retMap.put(key, ""));

        firstLevelList.forEach(item -> {
            String firstLevelName = item.getFirstLevelIndicatorName();
            // 优先处理第一级指标
            if (firstLevelMapping.containsKey(firstLevelName)) {
                retMap.put(firstLevelMapping.get(firstLevelName), item.getSecondLevelIndicatorValue());
            }
        });

        return retMap;
    }

    @Override
    public Map<String, Object> gxKypt(String highName) {
        Map<String, Object> retMap = new HashMap<>();

        // 国家级科研平台
        List<String> gjjkyptKeys = Arrays.asList(
                "全国重点实验室", "国家地方联合工程实验室", "国家工程技术研究中心",
                "国家地方联合工程研究中心", "国际联合研究中心", "国家大学科技园", "国际研发中心"
        );
        retMap.put("gjjkyptVoList", createIndicatorVoList( highName, "科研平台", "国家级科研平台", gjjkyptKeys));

        // 国家级项目
        List<String> gjjxmKeys = Arrays.asList(
                "国家重点研发计划", "国家科技部项目", "国家自然科学基金项目"
        );
        retMap.put("gjjxmVoList", createIndicatorVoList( highName, "科研平台", "国家级项目", gjjxmKeys));

        // 部委项目
        List<String> bwxmKeys = Arrays.asList(
                "国家部委其他科技项目", "教育部科技项目"
        );
        retMap.put("bwxmVoList", createIndicatorVoList( highName, "科研平台", "部委项目", bwxmKeys));

        // 其它科技项目
        List<String> qtkjxmKeys = Arrays.asList(
                "省市科技项目", "地市厅局项目", "企事业科技项目", "国际合作项目"
        );
        retMap.put("qtkjxmVoList", createIndicatorVoList(  highName, "科研平台", "其它科技项目", qtkjxmKeys));

        return retMap;
    }

    /**
     * 高校-学校治理KPI指标
     * @param highName 高校名
     * @return 高校指标
     * @author jfh
     * @date 2025-08-28
     */
    @Override
    public Map<String, UniversityIndicatorVo> gxXxzlKpi(String highName) {
        // KPI
        // 查询数据库
        List<UniversityIndicators> indicatorsList = Optional.ofNullable(universityIndicatorsMapper.selectList(
                new LambdaQueryWrapper<UniversityIndicators>()
                        .eq(UniversityIndicators::getSubModule, "关键绩效指标")
                        .eq(UniversityIndicators::getSecondLevelIndicatorName, highName)
        )).orElse(Collections.emptyList());

        Map<String, UniversityIndicatorVo> retMap = new HashMap<>();

        // 使用Map来存储映射关系，提高可读性和性能
        Map<String, String> firstLevelMapping = new HashMap<String, String>() {{
            put("高校专职辅导员配备率", "a");
            put("高校专职思政课教师配备率", "b");
            put("高校专职组织员配备率", "c");
            put("本校行政诉讼和知识产权诉讼案件数量", "d");
            put("涉教信访件（季）办结率", "e");
            put("数据归集与共享综合评分", "f");
            put("核心业务数字化率", "g");
            put("应用场景使用活跃度", "h");
            put("普通、职业高校具有硕士及以上学位的专任教师比例", "i");
        }};

        // 初始化所有可能的key到retMap，默认值包含指标名称，值为"0"
        firstLevelMapping.forEach((indicatorName, key) -> {
            UniversityIndicatorVo vo = new UniversityIndicatorVo();
            vo.setIndicatorName(indicatorName);
            vo.setIndicatorValue("-");
            vo.setTargetValue("-");
            retMap.put(key, vo);
        });

        // 填充从数据库查询到的实际数据
        indicatorsList.forEach(item -> {
            String firstLevelName = item.getFirstLevelIndicatorName();
            // 优先处理第一级指标
            if (firstLevelMapping.containsKey(firstLevelName)) {
                UniversityIndicatorVo vo = new UniversityIndicatorVo();
                vo.setIndicatorName(firstLevelName);
                vo.setIndicatorValue(item.getSecondLevelIndicatorValue());
                vo.setTargetValue(item.getSecondLevelTargetValue());
                retMap.put(firstLevelMapping.get(firstLevelName), vo);
            }
        });

        return retMap;
    }

    private List<UniversityIndicatorVo> createIndicatorVoList(
            String highName,
            String subModule,
            String firstLevelIndicatorName,
            List<String> keys) {

        // 查询数据库
        List<UniversityIndicators> indicatorsList = Optional.ofNullable(universityIndicatorsMapper.selectList(
                new LambdaQueryWrapper<UniversityIndicators>()
                        .eq(UniversityIndicators::getSubModule, subModule)
                        .eq(UniversityIndicators::getFirstLevelIndicatorName, firstLevelIndicatorName)
                        .eq(UniversityIndicators::getThirdLevelIndicatorName, highName)
        )).orElse(Collections.emptyList());

        // 转换为Map提高查找效率
        Map<String, String> indicatorMap = indicatorsList.stream()
                .filter(item -> item.getSecondLevelIndicatorName() != null)
                .collect(Collectors.toMap(
                        UniversityIndicators::getSecondLevelIndicatorName,
                        item -> item.getThirdLevelIndicatorValue() != null ?
                                item.getThirdLevelIndicatorValue() : "0",
                        (existing, replacement) -> existing));

        // 创建Vo列表
        return keys.stream()
                .map(key -> {
                    UniversityIndicatorVo vo = new UniversityIndicatorVo();
                    vo.setIndicatorName(key);
                    vo.setIndicatorValue(indicatorMap.getOrDefault(key, "0"));
                    return vo;
                })
                .collect(Collectors.toList());
    }


    private String toEnglishIndicatorKey(String name){
        switch (name){
            case "生师比":
                return "shengshibi";
            case "其它科技项目":
                return "qitakejixiangmu";
            case "部委项目":
                return "buweixiangmu";
            case "国家级项目":
                return "guojiajixiangmu";
            case "本科高校教师教学创新比赛":
                return "benkegaoxiaojiaoshijiaoxuechuangxinbisai";
            case "国家级教学成果奖":
                return "guojiajijiaoxuechengguojiang";
            case "高水平“四新”建设高校":
                return "gaoshuiping";
            case "国家级一流本科课程":
                return "guojiajiyiliubenkekecheng";
            case "国家级一流本科专业建设点":
                return "guojiajiyiliubenkezhuanyejianshedian";
            case "“双一流”建设入选学科":
                return "shuangyiliuxueke";
            case "市级重点学科":
                return "shijizhongdianxueke";
            case "博士学位授权点":
                return "boshixueweishouquandian";
            case "硕士学位授权点":
                return "shoushixueweishouquandian";
            case "市级高水平专业群建设单位":
                return "shijigaoshuipingzhuanye";
            case "市级高水平学校建设单位":
                return "shijigaoshuipingxuexiao";
            case "国家高水平专业群建设单位":
                return "guojiagaoshuipingzhuanye";
            case "国家高水平学校建设单位":
                return "guojiagaoshuipingxuexiao";
            case "“双一流”建设入选高校":
                return "shuangyiliugaoxiao";
            default:
                return "other";
        }
    }
    private String toShortKey(String subModule) {
        switch (subModule) {
            case "高层次人才情况":
                return "gaoceng";
            case "双一流、双高建设":
                return "shuang";
            case "学科专业建设":
                return "xueke";
            case "科研平台":
                return "keyan";
            default:
                return "other";
        }
    }
}
